"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import { Layout, Menu, Input, Avatar, Button, Dropdown, Badge } from "antd";
import { UserOutlined, BellOutlined, DownOutlined } from "@ant-design/icons";
import { useSelectedLayoutSegment, useRouter } from "next/navigation";
import { useUser } from "../context/userContext";
import api from "../utils/api";
import styles from "@/components/HomepageLayout.module.css"; // 引入 CSS 模块
import fontStyles from "@/components/Font.module.css"; // 引入 CSS 模块

const { Header, Content } = Layout;
const { Search } = Input;

export default function ForumLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const router = useRouter();
  const segment = useSelectedLayoutSegment();
  const selectedKey = segment === null ? "home" : segment;
  const { user } = useUser();
  const username = user?.username || null;
  const isAdmin = user?.role === "admin";
  const [unreadMessageCount, setUnreadMessageCount] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchAlerts = async () => {
      if (!user || !user.access_token) return;

      try {
        const headers = {
          Authorization: `Bearer ${user.access_token}`,
          "Content-Type": "application/json",
        };
        const params = { page: "1", pageSize: "10" };
        const response = await api.get("/alerts/getFromReceiver", {
          params,
          headers,
        });

        if (response.status === 200) {
          const { alerts = [] } = response.data || {};
          const unread = alerts.filter((alert) => alert.status === "unread");
          setUnreadMessageCount(unread.length);
          setError(null);
        } else {
          throw new Error(`状态码错误: ${response.status}`);
        }
      } catch (err) {
        console.error("获取消息失败:", err);
        setError(err.message || "获取消息失败");
        setUnreadMessageCount(0);
      } finally {
        setLoading(false);
      }
    };

    fetchAlerts();
  }, [user]);

  const messageDropdown = (
    <Menu>
      <Menu.Item key="1">
        <Badge
          count={unreadMessageCount && !loading ? unreadMessageCount : 0}
          size="small"
        >
          <Link href="/homepage/message">我的消息</Link>
        </Badge>
      </Menu.Item>
    </Menu>
  );

  return (
    <Layout style={{ backgroundColor: "transparent", height: "100vh" }}>
      <Header className={styles.header}>
        <div className={`${styles.headerTitle} ${fontStyles.cardTitle}`}>
          微百合论坛
        </div>

        <Menu
          theme="light"
          mode="horizontal"
          selectedKeys={[selectedKey]}
          className={`${fontStyles.text} ${styles.menu} `}
        >
          <Menu.Item key="home">
            <Link href="/homepage/home">首页</Link>
          </Menu.Item>
          <Menu.Item key="popular">
            <Link href="/homepage/popular">热门</Link>
          </Menu.Item>
          <Menu.Item key="about">
            <Link href="/homepage/about">关于</Link>
          </Menu.Item>
          {isAdmin && (
            <Menu.Item key="administrators">
              <Link href="/administrators">切换为管理员</Link>
            </Menu.Item>
          )}
        </Menu>
        <div className={styles.rightSection}>
          <Search
            className={styles.search}
            placeholder="搜索"
            onSearch={(value) => {
              const keyword = value.trim();
              if (keyword) router.push(`/homepage/search/${keyword}`);
            }}
          />

          <Dropdown overlay={messageDropdown} trigger={["click"]}>
            <Badge
              count={unreadMessageCount && !loading ? unreadMessageCount : 0}
              size="small"
              style={{ marginLeft: 20 }}
            >
              <Button
                type="text"
                icon={<BellOutlined />}
                style={{ fontSize: "18px" }}
              >
                <DownOutlined />
              </Button>
            </Badge>
          </Dropdown>

          {username ? (
            <Link href={`/profile/${username}`} passHref legacyBehavior>
              <a
                className={`${fontStyles.linkText} text-[24px]`}
                style={{
                  display: "flex",
                  alignItems: "center",
                  marginLeft: "10px",
                }}
              >
                <Avatar
                  src={`http://120.26.138.4:3000${user.icon}`}
                  size={50}
                  style={{ marginRight: "10px" }}
                />
                <span className={styles.username}>{user.display_name}</span>
              </a>
            </Link>
          ) : (
            <Link href="/login">
              <div style={{ marginLeft: "20px", cursor: "pointer" }}>
                <Avatar icon={<UserOutlined />} />
              </div>
            </Link>
          )}
        </div>
      </Header>

      <Content className={styles.layoutContent}>
        <div className={styles.innerContentWrapper}>{children}</div>
      </Content>
    </Layout>
  );
}
